package com.cloud.api.websockt.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;

import com.cloud.api.websockt.handler.GameEventHandler;

/**
 * websocket 配置类
 * 
 * @author cloudwei
 *
 */
@Configuration
public class WebSocketConfiguration {
	@Bean
	@Autowired
	public HandlerMapping websocketMapping(final GameEventHandler echoHandler) {
		/**
		 * 使用 map 指定 WebSocket 协议的路由，路由为 ws://localhost:8080/gameapi/bm/game
		 */
		final Map<String, WebSocketHandler> hanlderMap = new HashMap<>();
		hanlderMap.put("/bm/game", echoHandler);
		hanlderMap.put("/socket.io/", echoHandler);
		
		/**
		 * SimpleUrlHandlerMapping 指定了 WebSocket 的路由配置
		 */
		final SimpleUrlHandlerMapping urlHanlderMapping = new SimpleUrlHandlerMapping();
		urlHanlderMapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
		urlHanlderMapping.setUrlMap(hanlderMap);
		return urlHanlderMapping;
	}

	/**
	 * WebSocketHandlerAdapter 负责将 EchoHandler 处理类适配到 WebFlux 容器中
	 * 
	 * @return WebSocketHandlerAdapter
	 */
	@Bean
	public WebSocketHandlerAdapter handlerAdopter() {
		return new WebSocketHandlerAdapter();
	}
}
